/* global Cesium */
const defined = Cesium.defined;
const SceneMode = Cesium.SceneMode;

let _cameraParam = {};

/**
 * [changeSceneMode description]
 * 切换当前的视图显示模式，如果是3D模式则切换到2D,反之亦然
 * @Author   Mjc
 * @DateTime 2018-04-19T15:22:05+0800
 * @exports
 * @param    {[type]}                 scene 场景对象
 * @return   {[type]}
 */
function changeSceneMode(scene) {
    if (!defined(scene)) {
        throw new Error('需要传入一个scene');
    }

    initArgs(scene);
    _cameraParam = setOptions(scene);
    scene.mode === SceneMode.SCENE3D ? scene.morphTo2D(1.0) : scene.morphTo3D(1.0);
}

// 注册二三维转换事件的监听
function initArgs(scene) {
    let removeEvent = scene.morphComplete.addEventListener(function() {
        scene.camera.updateCamera(_cameraParam);
        removeEvent();
    });
}

// 记录摄像机参数的对象
function setOptions(scene) {
    let options = {
        position: null,
        direction: scene.camera.direction.clone(),
        up: scene.camera.up.clone(),
        frustum: scene.camera.saveFrustum(scene.camera.frustum.clone()),
    };

    if (scene.mode === SceneMode.SCENE3D) {
        options.position = scene.camera.positionWC.clone();
    } else {
        let cartographic = scene.mapProjection.unproject(scene.camera.position);
        cartographic.height = scene.camera.getViewHeight();
        options.position = scene.mapProjection.ellipsoid.cartographicToCartesian(cartographic);
    }

    return options;
}
export default changeSceneMode;
